using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Controls.Primitives;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 分步执行写书对话框
    /// </summary>
    public partial class StepByStepWritingDialog : Window
    {
        private readonly ILogger<StepByStepWritingDialog> _logger;
        private readonly StepByStepWritingService _stepByStepService;
        private readonly IBookBasicInfoService _bookBasicInfoService;
        private readonly UnifiedChapterSaveService _chapterSaveService;
        private StepByStepWritingService.StepExecutionState? _currentState;
        private CancellationTokenSource? _cancellationTokenSource;

        // 执行状态控制
        private bool _isExecuting = false;
        private bool _isPaused = false;
        private Task? _currentExecutionTask;

        // 当前项目信息
        public Project? CurrentProject { get; set; }
        
        // 事件
        public event EventHandler? ProjectNavigationRefreshRequested;
        public event EventHandler<string>? DocumentEditorUpdateRequested;

        public StepByStepWritingDialog(
            ILogger<StepByStepWritingDialog> logger,
            StepByStepWritingService stepByStepService,
            IBookBasicInfoService bookBasicInfoService,
            UnifiedChapterSaveService chapterSaveService)
        {
            InitializeComponent();
            _logger = logger;
            _stepByStepService = stepByStepService;
            _bookBasicInfoService = bookBasicInfoService;
            _chapterSaveService = chapterSaveService;

            InitializeUI();
        }

        private async void InitializeUI()
        {
            // 设置默认值
            VolumeCountTextBox.Text = "10"; // 默认10卷
            ChapterCountTextBox.Text = "100"; // 默认100章
            WordsPerChapterTextBox.Text = "6500"; // 默认每章6500字
            TargetWordCountTextBox.Text = "650000"; // 默认总字数65万
            SegmentWordsTextBox.Text = "1000"; // 默认分段1000字
            ReviewChaptersTextBox.Text = "3"; // 默认回顾3章

            // 设置默认选项
            GenreComboBox.SelectedIndex = 0; // 默认都市修仙
            WritingStyleComboBox.SelectedIndex = 0; // 默认流畅自然
            AutoSaveCheckBox.IsChecked = true;
            GenerateOutlineFirstCheckBox.IsChecked = true;
            UseReferenceContentCheckBox.IsChecked = true;

            // 添加卷数文本框验证
            VolumeCountTextBox.TextChanged += VolumeCountTextBox_TextChanged;

            // 添加字数计算功能
            TargetWordCountTextBox.TextChanged += (s, e) => UpdateChapterCount();
            WordsPerChapterTextBox.TextChanged += (s, e) => UpdateChapterCount();

            // 初始化步骤图标
            UpdateStepIcons();

            // 初始化执行按钮状态
            UpdateExecutionButtonStates();

            // 检查网络状态
            await CheckNetworkStatusAsync();

            // 尝试自动加载书籍基本信息
            await AutoLoadBasicInfo();

            _logger.LogInformation("分步执行写书对话框已初始化");
        }

        /// <summary>
        /// 根据总字数和每章字数自动计算章节数
        /// </summary>
        private void UpdateChapterCount()
        {
            try
            {
                if (int.TryParse(TargetWordCountTextBox.Text, out var totalWords) &&
                    int.TryParse(WordsPerChapterTextBox.Text, out var wordsPerChapter) &&
                    wordsPerChapter > 0)
                {
                    var calculatedChapters = totalWords / wordsPerChapter;
                    ChapterCountTextBox.Text = calculatedChapters.ToString();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "计算章节数失败");
            }
        }

        /// <summary>
        /// 验证卷数输入
        /// </summary>
        private void VolumeCountTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (int.TryParse(VolumeCountTextBox.Text, out int volumeCount))
            {
                if (volumeCount >= 1 && volumeCount <= 50)
                {
                    VolumeCountValidationText.Visibility = Visibility.Collapsed;
                }
                else
                {
                    VolumeCountValidationText.Visibility = Visibility.Visible;
                }
            }
            else
            {
                VolumeCountValidationText.Visibility = Visibility.Visible;
            }
        }

        private void UpdateStepIcons()
        {
            if (_currentState == null)
            {
                // 重置所有图标
                Step1Icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.Circle;
                Step2Icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.Earth;
                Step3Icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.Circle;
                Step4Icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.FileDocument;
                Step5Icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.FileText;

                Step1Icon.Foreground = Brushes.Gray;
                Step2Icon.Foreground = Brushes.Gray;
                Step3Icon.Foreground = Brushes.Gray;
                Step4Icon.Foreground = Brushes.Gray;
                Step5Icon.Foreground = Brushes.Gray;
                return;
            }

            // 更新步骤图标状态（新的步骤顺序）
            UpdateStepIcon(Step1Icon, _currentState.OverallOutlineCompleted);
            UpdateStepIcon(Step2Icon, _currentState.WorldSettingCompleted);
            UpdateStepIcon(Step3Icon, _currentState.VolumeOutlinesCompleted);
            UpdateStepIcon(Step4Icon, _currentState.ChapterOutlines.Any());
            UpdateStepIcon(Step5Icon, _currentState.ChapterContents.Any());

            // 更新按钮状态（新的流程顺序）
            GenerateWorldSettingButton.IsEnabled = _currentState.OverallOutlineCompleted && !_isExecuting;
            GenerateVolumeOutlinesButton.IsEnabled = _currentState.OverallOutlineCompleted && _currentState.WorldSettingCompleted && !_isExecuting;
            VolumeSelectionComboBox.IsEnabled = _currentState.VolumeOutlinesCompleted;
            GenerateChapterOutlinesButton.IsEnabled = _currentState.VolumeOutlinesCompleted && !_isExecuting;
            ChapterNumberTextBox.IsEnabled = _currentState.ChapterOutlines.Any();
            GenerateChapterContentButton.IsEnabled = _currentState.ChapterOutlines.Any() && !_isExecuting;

            // 批量生成按钮状态
            if (BatchGenerateChaptersButton != null)
            {
                BatchGenerateChaptersButton.IsEnabled = _currentState.ChapterOutlines.Any() && !_isExecuting;
            }

            // 逐章生成按钮状态
            if (SequentialGenerateChapterButton != null)
            {
                SequentialGenerateChapterButton.IsEnabled = _currentState.VolumeOutlinesCompleted && !_isExecuting && !_isSequentialGenerating;
            }

            // 更新逐章连续生成按钮状态
            UpdateSequentialGenerationButtonStates();

            // 更新状态摘要
            StateSummaryText.Text = _stepByStepService.GetStateSummary(_currentState);
            
            // 更新卷宗选择下拉框
            if (_currentState.VolumeOutlinesCompleted && _currentState.VolumeOutlines.Any())
            {
                VolumeSelectionComboBox.Items.Clear();
                foreach (var volume in _currentState.VolumeOutlines)
                {
                    VolumeSelectionComboBox.Items.Add($"第{volume.VolumeNumber}卷 - {volume.Title}");
                }
                if (VolumeSelectionComboBox.Items.Count > 0)
                {
                    VolumeSelectionComboBox.SelectedIndex = 0;
                }
            }
        }

        private void UpdateStepIcon(MaterialDesignThemes.Wpf.PackIcon icon, bool isCompleted)
        {
            if (isCompleted)
            {
                icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
                icon.Foreground = Brushes.Green;
            }
            else
            {
                // 保持原始图标类型，只改变颜色
                icon.Foreground = Brushes.Gray;
            }
        }

        /// <summary>
        /// 批量生成章节正文
        /// </summary>
        private async void BatchGenerateChapters_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null || !_currentState.ChapterOutlines.Any())
                    return;

                // 获取要生成的章节范围
                var result = await ShowBatchGenerationDialogAsync();
                if (!result.Item1) return;

                int startChapter = result.Item2;
                int endChapter = result.Item3;

                // 开始批量生成
                await StartBatchGenerationAsync(startChapter, endChapter);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量生成章节时出错");
                MessageBox.Show($"批量生成章节时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 显示批量生成对话框
        /// </summary>
        private Task<Tuple<bool, int, int>> ShowBatchGenerationDialogAsync()
        {
            // 这里实现批量生成对话框
            // 返回: 是否确认, 开始章节, 结束章节
            var tcs = new TaskCompletionSource<Tuple<bool, int, int>>();

            // 简单实现，后续可以改为自定义对话框
            var startChapter = 1;
            var endChapter = _currentState?.ChapterOutlines.Keys.Max() ?? 1;

            var result = MessageBox.Show($"将批量生成第{startChapter}章到第{endChapter}章的正文，是否继续？",
                "批量生成确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                tcs.SetResult(new Tuple<bool, int, int>(true, startChapter, endChapter));
            }
            else
            {
                tcs.SetResult(new Tuple<bool, int, int>(false, 0, 0));
            }

            return tcs.Task;
        }

        /// <summary>
        /// 开始批量生成章节
        /// </summary>
        private async Task StartBatchGenerationAsync(int startChapter, int endChapter)
        {
            try
            {
                _isExecuting = true;
                UpdateExecutionButtonStates();

                var totalChapters = endChapter - startChapter + 1;
                var completedChapters = 0;

                ExecutionProgressBar.Visibility = Visibility.Visible;
                ExecutionProgressBar.Value = 0;

                for (int chapterNumber = startChapter; chapterNumber <= endChapter; chapterNumber++)
                {
                    if (_cancellationTokenSource?.Token.IsCancellationRequested == true)
                        break;

                    UpdateUI($"正在生成第{chapterNumber}章正文...", true);

                    var result = await _stepByStepService.GenerateChapterContentAsync(_currentState, chapterNumber, _cancellationTokenSource?.Token ?? CancellationToken.None);

                    if (result.IsSuccess)
                    {
                        // 保存为指定格式的文件
                        await SaveChapterToFileAsync(chapterNumber, result.Data?.ToString() ?? "");

                        completedChapters++;
                        var progressPercentage = (int)((double)completedChapters / totalChapters * 100);
                        ExecutionProgressBar.Value = progressPercentage;

                        UpdateUI($"第{chapterNumber}章正文生成完成 ({completedChapters}/{totalChapters})", false);

                        // 更新时间线（如果需要）
                        await UpdateTimelineAfterChapterAsync(chapterNumber);

                        // 调整下一章的细纲（如果存在）
                        if (chapterNumber < endChapter && _currentState.ChapterOutlines.ContainsKey(chapterNumber + 1))
                        {
                            await AdjustNextChapterOutlineAsync(chapterNumber, result.Data?.ToString() ?? "");
                        }
                    }
                    else
                    {
                        _logger.LogError($"第{chapterNumber}章生成失败: {result.Message}");
                        UpdateUI($"第{chapterNumber}章生成失败: {result.Message}", false);
                    }

                    // 保存状态
                    await _stepByStepService.SaveStateAsync(_currentState);
                }

                ExecutionProgressBar.Visibility = Visibility.Collapsed;
                UpdateUI($"批量生成完成，共生成{completedChapters}章", false);

                // 触发项目导航刷新
                ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量生成章节失败");
                UpdateUI($"批量生成失败: {ex.Message}", false);
            }
            finally
            {
                _isExecuting = false;
                UpdateExecutionButtonStates();
                ExecutionProgressBar.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 保存章节内容到文件
        /// </summary>
        private async Task SaveChapterToFileAsync(int chapterNumber, string content)
        {
            try
            {
                if (_currentState == null || string.IsNullOrEmpty(content))
                    return;

                // 获取章节标题
                string chapterTitle = "未命名章节";
                if (_currentState.ChapterTitles.ContainsKey(chapterNumber))
                {
                    chapterTitle = _currentState.ChapterTitles[chapterNumber];
                }
                else
                {
                    // 尝试从内容中提取标题
                    var titleMatch = System.Text.RegularExpressions.Regex.Match(content, @"^第.+?章[：:]\s*(.+?)[\r\n]");
                    if (titleMatch.Success && titleMatch.Groups.Count > 1)
                    {
                        chapterTitle = titleMatch.Groups[1].Value.Trim();
                        _currentState.ChapterTitles[chapterNumber] = chapterTitle;
                    }
                }

                // 构建文件名 - 使用统一的命名格式
                string fileName;
                var volumeInfo = _currentState.VolumeOutlines.FirstOrDefault(v =>
                    chapterNumber >= v.StartChapter && chapterNumber <= v.EndChapter);

                if (volumeInfo != null)
                {
                    fileName = $"{_currentState.BookTitle}_第{volumeInfo.VolumeNumber:D2}卷_{volumeInfo.Title}_第{chapterNumber:D3}章_{chapterTitle}";
                }
                else
                {
                    fileName = $"{_currentState.BookTitle}_第{chapterNumber:D3}章_{chapterTitle}";
                }

                // 获取选择的文件格式，默认为.txt
                string fileExtension = ".txt";

                // 即使有选择，也强制使用.txt格式
                // 如果将来需要支持其他格式，可以取消下面的注释
                /*
                if (FileFormatComboBox.SelectedItem is ComboBoxItem selectedItem && selectedItem.Tag != null)
                {
                    fileExtension = $".{selectedItem.Tag}";
                }
                */

                // 保存文件
                string filePath = System.IO.Path.Combine(_currentState.ProjectPath, "章节", fileName + fileExtension);

                // 确保目录存在
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));

                // 统一保存为纯文本格式
                await System.IO.File.WriteAllTextAsync(filePath, content, System.Text.Encoding.UTF8);

                _logger.LogInformation($"已保存章节内容到文件: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存章节内容到文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存为Word文档
        /// </summary>
        private async Task SaveAsDocxAsync(string filePath, string title, string content)
        {
            // 这里需要实现Word文档保存逻辑
            // 可以使用DocumentFormat.OpenXml或其他库

            // 简单实现，后续可以改进
            await Task.Run(() => {
                // 创建一个临时文本文件
                var tempFile = System.IO.Path.ChangeExtension(filePath, ".txt");
                System.IO.File.WriteAllText(tempFile, $"标题: {title}\r\n\r\n{content}");

                // 提示用户手动转换
                _logger.LogWarning("Word文档保存功能尚未实现，已保存为临时文本文件: " + tempFile);
            });
        }

        /// <summary>
        /// 更新时间线
        /// </summary>
        private async Task UpdateTimelineAfterChapterAsync(int chapterNumber)
        {
            try
            {
                if (_currentState == null)
                    return;

                // 获取章节内容
                if (!_currentState.ChapterContents.ContainsKey(chapterNumber))
                    return;

                var chapterContent = _currentState.ChapterContents[chapterNumber];

                // 更新时间线文件
                var timelinePath = System.IO.Path.Combine(_currentState.ProjectPath, "Settings", "时间线管理.md");

                // 确保目录存在
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(timelinePath));

                // 读取现有时间线
                string existingTimeline = "";
                if (System.IO.File.Exists(timelinePath))
                {
                    existingTimeline = await System.IO.File.ReadAllTextAsync(timelinePath);
                }

                // 提取章节中的时间线信息
                // 这里需要实现时间线提取逻辑，可以使用AI服务

                // 简单实现，后续可以改进
                var timelineUpdate = $"\n## 第{chapterNumber}章时间线更新\n\n";
                timelineUpdate += $"- 章节标题: {_currentState.ChapterTitles.GetValueOrDefault(chapterNumber, $"第{chapterNumber}章")}\n";
                timelineUpdate += $"- 更新时间: {DateTime.Now}\n";
                timelineUpdate += $"- 内容摘要: {(chapterContent.Length > 100 ? chapterContent.Substring(0, 100) + "..." : chapterContent)}\n";

                // 更新时间线文件
                await System.IO.File.AppendAllTextAsync(timelinePath, timelineUpdate);

                _logger.LogInformation($"已更新时间线: {timelinePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新时间线失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 调整下一章的细纲
        /// </summary>
        private async Task AdjustNextChapterOutlineAsync(int currentChapter, string currentContent)
        {
            try
            {
                if (_currentState == null)
                    return;

                var nextChapter = currentChapter + 1;
                if (!_currentState.ChapterOutlines.ContainsKey(nextChapter))
                    return;

                // 这里需要实现调整下一章细纲的逻辑
                // 可以使用AI服务根据当前章节内容调整下一章的细纲

                _logger.LogInformation($"已调整第{nextChapter}章细纲");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"调整下一章细纲失败: {ex.Message}");
            }
        }

        private async void GenerateOverallOutline_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ValidateBasicInfo())
                    return;

                await InitializeStateIfNeededAsync();
                if (_currentState == null)
                    return;

                UpdateUI("正在生成全书大纲...", true);
                
                _cancellationTokenSource = new CancellationTokenSource();
                var result = await _stepByStepService.GenerateOverallOutlineAsync(_currentState, _cancellationTokenSource.Token);
                
                if (result.IsSuccess)
                {
                    ContentDisplayTextBox.Text = result.Data?.ToString() ?? "";
                    ContentTitleText.Text = "全书大纲";
                    UpdateStepIcons();
                    await _stepByStepService.SaveStateAsync(_currentState);
                    UpdateUI("全书大纲生成完成", false);
                    
                    // 触发项目导航刷新
                    ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    UpdateUI($"生成失败: {result.Message}", false);
                    if (!string.IsNullOrEmpty(result.ErrorDetails))
                    {
                        _logger.LogError($"生成全书大纲失败: {result.ErrorDetails}");

                        // 如果是网络错误，显示网络状态
                        if (IsNetworkError(result.ErrorDetails))
                        {
                            await CheckNetworkStatusAsync();
                            MessageBox.Show($"{result.Message}\n\n建议：\n1. 检查网络连接\n2. 稍后重试\n3. 系统会自动重试网络请求",
                                "网络连接问题", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成全书大纲时发生错误");
                UpdateUI("生成全书大纲时发生错误", false);
                MessageBox.Show($"生成全书大纲时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void GenerateVolumeOutlines_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null || !_currentState.OverallOutlineCompleted)
                {
                    MessageBox.Show("请先生成全书大纲", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                UpdateUI("正在生成卷宗大纲...", true);
                
                var progress = new Progress<int>(percentage => 
                {
                    Dispatcher.Invoke(() => 
                    {
                        ExecutionProgressBar.Value = percentage;
                    });
                });
                
                _cancellationTokenSource = new CancellationTokenSource();
                var result = await _stepByStepService.GenerateVolumeOutlinesAsync(_currentState, progress, _cancellationTokenSource.Token);
                
                if (result.IsSuccess)
                {
                    var volumeOutlines = result.Data as System.Collections.Generic.List<VolumeOutline>;
                    if (volumeOutlines != null)
                    {
                        var displayText = string.Join("\n\n", volumeOutlines.Select(v => 
                            $"第{v.VolumeNumber}卷：{v.Title}\n{v.Description}"));
                        ContentDisplayTextBox.Text = displayText;
                        ContentTitleText.Text = $"卷宗大纲 (共{volumeOutlines.Count}卷)";
                    }
                    
                    UpdateStepIcons();
                    await _stepByStepService.SaveStateAsync(_currentState);
                    UpdateUI("卷宗大纲生成完成", false);
                    
                    // 触发项目导航刷新
                    ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    UpdateUI($"生成失败: {result.Message}", false);
                    if (!string.IsNullOrEmpty(result.ErrorDetails))
                    {
                        _logger.LogError($"生成卷宗大纲失败: {result.ErrorDetails}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成卷宗大纲时发生错误");
                UpdateUI("生成卷宗大纲时发生错误", false);
                MessageBox.Show($"生成卷宗大纲时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void GenerateChapterOutlines_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null || !_currentState.VolumeOutlinesCompleted)
                {
                    MessageBox.Show("请先生成卷宗大纲", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (VolumeSelectionComboBox.SelectedIndex < 0)
                {
                    MessageBox.Show("请选择要生成章节细纲的卷宗", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var volumeNumber = VolumeSelectionComboBox.SelectedIndex + 1;
                UpdateUI($"正在生成第{volumeNumber}卷章节细纲...", true);
                
                var progress = new Progress<int>(percentage => 
                {
                    Dispatcher.Invoke(() => 
                    {
                        ExecutionProgressBar.Value = percentage;
                    });
                });
                
                _cancellationTokenSource = new CancellationTokenSource();
                var result = await _stepByStepService.GenerateChapterOutlinesForVolumeAsync(_currentState, volumeNumber, progress, _cancellationTokenSource.Token);
                
                if (result.IsSuccess)
                {
                    var volume = _currentState.VolumeOutlines.FirstOrDefault(v => v.VolumeNumber == volumeNumber);
                    if (volume != null)
                    {
                        var chapterOutlines = _currentState.ChapterOutlines
                            .Where(kv => kv.Key >= volume.StartChapter && kv.Key <= volume.EndChapter)
                            .OrderBy(kv => kv.Key)
                            .Select(kv => $"第{kv.Key}章细纲：\n{kv.Value}")
                            .ToList();
                        
                        ContentDisplayTextBox.Text = string.Join("\n\n", chapterOutlines);
                        ContentTitleText.Text = $"第{volumeNumber}卷章节细纲 (共{result.Data}章)";
                    }
                    
                    UpdateStepIcons();
                    await _stepByStepService.SaveStateAsync(_currentState);
                    UpdateUI($"第{volumeNumber}卷章节细纲生成完成", false);
                    
                    // 触发项目导航刷新
                    ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    UpdateUI($"生成失败: {result.Message}", false);
                    if (!string.IsNullOrEmpty(result.ErrorDetails))
                    {
                        _logger.LogError($"生成章节细纲失败: {result.ErrorDetails}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成章节细纲时发生错误");
                UpdateUI("生成章节细纲时发生错误", false);
                MessageBox.Show($"生成章节细纲时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void GenerateChapterContent_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null || !_currentState.ChapterOutlines.Any())
                {
                    MessageBox.Show("请先生成章节细纲", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (!int.TryParse(ChapterNumberTextBox.Text, out int chapterNumber) || chapterNumber <= 0)
                {
                    MessageBox.Show("请输入有效的章节号", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (!_currentState.ChapterOutlines.ContainsKey(chapterNumber))
                {
                    MessageBox.Show($"第{chapterNumber}章的细纲尚未生成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                UpdateUI($"正在生成第{chapterNumber}章正文...", true);

                _cancellationTokenSource = new CancellationTokenSource();
                var result = await _stepByStepService.GenerateChapterContentAsync(_currentState, chapterNumber, _cancellationTokenSource.Token);

                if (result.IsSuccess)
                {
                    ContentDisplayTextBox.Text = result.Data?.ToString() ?? "";
                    ContentTitleText.Text = $"第{chapterNumber}章正文";
                    UpdateStepIcons();
                    await _stepByStepService.SaveStateAsync(_currentState);
                    UpdateUI($"第{chapterNumber}章正文生成完成", false);

                    // 更新文档编辑器
                    DocumentEditorUpdateRequested?.Invoke(this, $"第{chapterNumber}章正文已生成\n\n{result.Data}\n\n");

                    // 触发项目导航刷新
                    ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    UpdateUI($"生成失败: {result.Message}", false);
                    if (!string.IsNullOrEmpty(result.ErrorDetails))
                    {
                        _logger.LogError($"生成章节正文失败: {result.ErrorDetails}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成章节正文时发生错误");
                UpdateUI("生成章节正文时发生错误", false);
                MessageBox.Show($"生成章节正文时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void GenerateWorldSetting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ValidateBasicInfo())
                    return;

                await InitializeStateIfNeededAsync();
                if (_currentState == null)
                    return;

                UpdateUI("正在生成世界设定...", true);

                _cancellationTokenSource = new CancellationTokenSource();
                var result = await _stepByStepService.GenerateWorldSettingAsync(_currentState, _cancellationTokenSource.Token);

                if (result.IsSuccess)
                {
                    ContentDisplayTextBox.Text = "世界设定已生成并保存到项目文件夹的Settings目录中";
                    ContentTitleText.Text = "世界设定";
                    UpdateStepIcons();
                    await _stepByStepService.SaveStateAsync(_currentState);
                    UpdateUI("世界设定生成完成", false);

                    // 触发项目导航刷新
                    ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    UpdateUI($"生成失败: {result.Message}", false);
                    if (!string.IsNullOrEmpty(result.ErrorDetails))
                    {
                        _logger.LogError($"生成世界设定失败: {result.ErrorDetails}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成世界设定时发生错误");
                UpdateUI("生成世界设定时发生错误", false);
                MessageBox.Show($"生成世界设定时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void SaveState_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null)
                {
                    MessageBox.Show("没有可保存的状态", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                await _stepByStepService.SaveStateAsync(_currentState);
                MessageBox.Show("状态已保存", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存状态时发生错误");
                MessageBox.Show($"保存状态时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void LoadState_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (CurrentProject == null)
                {
                    MessageBox.Show("请先选择项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var state = await _stepByStepService.LoadStateAsync(CurrentProject.RootPath);
                if (state != null)
                {
                    _currentState = state;

                    // 更新UI显示
                    BookTitleTextBox.Text = state.BookTitle;
                    CreativeDirectionTextBox.Text = state.CreativeDirection;
                    VolumeCountTextBox.Text = state.VolumeCount.ToString();
                    ChapterCountTextBox.Text = state.ChapterCount.ToString();
                    WordsPerChapterTextBox.Text = state.WordsPerChapter.ToString();

                    UpdateStepIcons();
                    ProjectStatusText.Text = $"项目: {state.BookTitle} | 已加载执行状态";

                    MessageBox.Show("状态已加载", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("未找到保存的状态文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载状态时发生错误");
                MessageBox.Show($"加载状态时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void StartExecution_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_isExecuting)
                {
                    MessageBox.Show("已有执行任务在进行中", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (!ValidateBasicInfo())
                    return;

                // 检查AI服务状态
                if (!await CheckAIServiceStatusAsync())
                    return;

                await InitializeStateIfNeededAsync();
                if (_currentState == null)
                    return;

                _isExecuting = true;
                _isPaused = false;
                _cancellationTokenSource = new CancellationTokenSource();

                UpdateExecutionButtonStates();
                UpdateUI("开始自动执行写书流程...", true);

                _currentExecutionTask = ExecuteFullWritingProcessAsync(_cancellationTokenSource.Token);
                await _currentExecutionTask;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始执行时发生错误");
                MessageBox.Show($"开始执行时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isExecuting = false;
                _isPaused = false;
                UpdateExecutionButtonStates();
                UpdateUI("执行完成", false);
            }
        }

        private void PauseExecution_Click(object sender, RoutedEventArgs e)
        {
            if (!_isExecuting)
            {
                MessageBox.Show("当前没有执行任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            _isPaused = true;
            UpdateExecutionButtonStates();
            UpdateUI("执行已暂停", false);
            _logger.LogInformation("用户暂停了执行");
        }

        private void ContinueExecution_Click(object sender, RoutedEventArgs e)
        {
            if (!_isExecuting || !_isPaused)
            {
                MessageBox.Show("当前没有暂停的执行任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            _isPaused = false;
            UpdateExecutionButtonStates();
            UpdateUI("继续执行...", true);
            _logger.LogInformation("用户继续了执行");
        }

        private void StopExecution_Click(object sender, RoutedEventArgs e)
        {
            if (!_isExecuting)
            {
                MessageBox.Show("当前没有执行任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var result = MessageBox.Show("确定要停止当前执行吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                _cancellationTokenSource?.Cancel();
                _isExecuting = false;
                _isPaused = false;
                UpdateExecutionButtonStates();
                UpdateUI("执行已停止", false);
                _logger.LogInformation("用户停止了执行");
            }
        }

        private void UpdateExecutionButtonStates()
        {
            Dispatcher.Invoke(() =>
            {
                if (!_isExecuting)
                {
                    // 未执行状态
                    StartExecutionButton.Visibility = Visibility.Visible;
                    PauseExecutionButton.Visibility = Visibility.Collapsed;
                    ContinueExecutionButton.Visibility = Visibility.Collapsed;
                    StopExecutionButton.Visibility = Visibility.Collapsed;
                }
                else if (_isPaused)
                {
                    // 暂停状态
                    StartExecutionButton.Visibility = Visibility.Collapsed;
                    PauseExecutionButton.Visibility = Visibility.Collapsed;
                    ContinueExecutionButton.Visibility = Visibility.Visible;
                    StopExecutionButton.Visibility = Visibility.Visible;
                }
                else
                {
                    // 执行状态
                    StartExecutionButton.Visibility = Visibility.Collapsed;
                    PauseExecutionButton.Visibility = Visibility.Visible;
                    ContinueExecutionButton.Visibility = Visibility.Collapsed;
                    StopExecutionButton.Visibility = Visibility.Visible;
                }
            });
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            _cancellationTokenSource?.Cancel();
            UpdateUI("操作已取消", false);
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            _cancellationTokenSource?.Cancel();
            Close();
        }

        /// <summary>
        /// 执行完整的写书流程
        /// </summary>
        private async Task ExecuteFullWritingProcessAsync(CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始执行完整写书流程");

                // 步骤1：生成世界设定
                if (!_currentState.WorldSettingCompleted)
                {
                    await WaitIfPausedAsync(cancellationToken);
                    UpdateUI("正在生成世界设定...", true);

                    var result = await _stepByStepService.GenerateWorldSettingAsync(_currentState, cancellationToken);
                    if (result.IsSuccess)
                    {
                        ContentDisplayTextBox.Text = "世界设定已生成并保存到项目文件夹的Settings目录中";
                        ContentTitleText.Text = "世界设定";
                        UpdateStepIcons();
                        await _stepByStepService.SaveStateAsync(_currentState);
                        ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                        _logger.LogInformation("世界设定生成完成");
                    }
                    else
                    {
                        throw new Exception($"生成世界设定失败：{result.Message}");
                    }
                }

                // 步骤2：生成全书大纲
                if (!_currentState.OverallOutlineCompleted)
                {
                    await WaitIfPausedAsync(cancellationToken);
                    UpdateUI("正在生成全书大纲...", true);

                    var result = await _stepByStepService.GenerateOverallOutlineAsync(_currentState, cancellationToken);
                    if (result.IsSuccess)
                    {
                        ContentDisplayTextBox.Text = result.Data?.ToString() ?? "";
                        ContentTitleText.Text = "全书大纲";
                        UpdateStepIcons();
                        await _stepByStepService.SaveStateAsync(_currentState);
                        ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                        _logger.LogInformation("全书大纲生成完成");
                    }
                    else
                    {
                        var errorMessage = $"生成全书大纲失败：{result.Message}";
                        if (!string.IsNullOrEmpty(result.ErrorDetails))
                        {
                            errorMessage += $"\n详细错误：{result.ErrorDetails}";
                        }
                        _logger.LogError($"全书大纲生成失败: {errorMessage}");
                        throw new Exception(errorMessage);
                    }
                }

                // 步骤3：生成分卷大纲
                if (!_currentState.VolumeOutlinesCompleted)
                {
                    await WaitIfPausedAsync(cancellationToken);
                    UpdateUI("正在生成分卷大纲...", true);

                    var progress = new Progress<int>(percentage =>
                    {
                        Dispatcher.Invoke(() =>
                        {
                            ExecutionProgressBar.Value = percentage;
                        });
                    });

                    var result = await _stepByStepService.GenerateVolumeOutlinesAsync(_currentState, progress, cancellationToken);
                    if (result.IsSuccess)
                    {
                        var volumeOutlines = result.Data as System.Collections.Generic.List<VolumeOutline>;
                        if (volumeOutlines != null)
                        {
                            var displayText = string.Join("\n\n", volumeOutlines.Select(v =>
                                $"第{v.VolumeNumber}卷：{v.Title}\n{v.Description}"));
                            ContentDisplayTextBox.Text = displayText;
                            ContentTitleText.Text = $"分卷大纲 (共{volumeOutlines.Count}卷)";
                        }

                        UpdateStepIcons();
                        await _stepByStepService.SaveStateAsync(_currentState);
                        ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                        _logger.LogInformation("分卷大纲生成完成");
                    }
                    else
                    {
                        throw new Exception($"生成分卷大纲失败：{result.Message}");
                    }
                }

                // 步骤4：按卷逐章生成（分卷大纲 → 逐章生成：细纲→正文→时间线）
                if (_currentState.VolumeOutlinesCompleted && _currentState.VolumeOutlines.Any())
                {
                    foreach (var volume in _currentState.VolumeOutlines.OrderBy(v => v.VolumeNumber))
                    {
                        await WaitIfPausedAsync(cancellationToken);
                        _logger.LogInformation($"开始处理第{volume.VolumeNumber}卷：{volume.Title}");

                        var startChapter = volume.StartChapter;
                        var endChapter = volume.EndChapter;

                        // 检查该卷是否已完成所有章节
                        bool volumeCompleted = true;
                        for (int ch = startChapter; ch <= endChapter; ch++)
                        {
                            if (!_currentState.ChapterContents.ContainsKey(ch))
                            {
                                volumeCompleted = false;
                                break;
                            }
                        }

                        if (volumeCompleted)
                        {
                            _logger.LogInformation($"第{volume.VolumeNumber}卷已完成，跳过");
                            continue;
                        }

                        UpdateUI($"开始处理第{volume.VolumeNumber}卷：{volume.Title}...", true);

                        // 逐章生成该卷的内容
                        for (int chapterNumber = startChapter; chapterNumber <= endChapter; chapterNumber++)
                        {
                            await WaitIfPausedAsync(cancellationToken);

                            // 检查该章节是否已完成
                            if (_currentState.ChapterContents.ContainsKey(chapterNumber))
                            {
                                _logger.LogInformation($"第{chapterNumber}章已完成，跳过");
                                continue;
                            }

                            _logger.LogInformation($"开始逐章生成第{chapterNumber}章");
                            UpdateUI($"正在生成第{chapterNumber}章（第{volume.VolumeNumber}卷）...", true);

                            var progress = new Progress<int>(percentage =>
                            {
                                Dispatcher.Invoke(() =>
                                {
                                    ExecutionProgressBar.Value = percentage;
                                    if (percentage == 10)
                                        UpdateUI($"正在生成第{chapterNumber}章细纲...", true);
                                    else if (percentage == 50)
                                        UpdateUI($"正在生成第{chapterNumber}章正文...", true);
                                    else if (percentage == 80)
                                        UpdateUI($"正在更新第{chapterNumber}章时间线...", true);
                                });
                            });

                            var result = await _stepByStepService.GenerateChapterSequentiallyAsync(
                                _currentState, chapterNumber, progress, cancellationToken);

                            if (result.IsSuccess)
                            {
                                ContentDisplayTextBox.Text = result.Data?.ToString() ?? "";
                                ContentTitleText.Text = $"第{chapterNumber}章正文";

                                // 保存章节内容到文件
                                await SaveChapterToFileAsync(chapterNumber, result.Data?.ToString() ?? "");

                                UpdateStepIcons();
                                await _stepByStepService.SaveStateAsync(_currentState);
                                ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);

                                // 更新文档编辑器
                                DocumentEditorUpdateRequested?.Invoke(this, $"第{chapterNumber}章正文已生成\n\n{result.Data}\n\n");

                                _logger.LogInformation($"第{chapterNumber}章逐章生成完成");

                                // 避免API限制，每章之间添加延迟
                                await Task.Delay(2000, cancellationToken);
                            }
                            else
                            {
                                throw new Exception($"生成第{chapterNumber}章失败：{result.Message}");
                            }
                        }

                        _logger.LogInformation($"第{volume.VolumeNumber}卷所有章节生成完成");
                    }
                }

                UpdateUI("完整写书流程执行完成！", false);
                MessageBox.Show($"恭喜！完整写书流程已执行完成！\n\n生成内容包括：\n- 世界设定\n- 全书大纲\n- 分卷大纲\n- 逐章生成（细纲→正文→时间线）\n- 章节正文 (共{_currentState.ChapterContents.Count}章)", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
            {
                UpdateUI("执行已取消", false);
                _logger.LogInformation("完整写书流程执行被用户取消");
                // 用户主动取消，不显示错误消息
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行完整写书流程时发生错误");
                UpdateUI($"执行失败：{ex.Message}", false);

                // 提供更详细的错误信息和恢复建议
                var errorMessage = GetDetailedErrorMessage(ex);
                var result = MessageBox.Show($"{errorMessage}\n\n是否要查看详细的错误信息？",
                    "执行失败", MessageBoxButton.YesNo, MessageBoxImage.Error);

                if (result == MessageBoxResult.Yes)
                {
                    ShowDetailedErrorDialog(ex);
                }
            }
            finally
            {
                _isExecuting = false;
                _isPaused = false;
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = null;
                UpdateExecutionButtonStates();
            }
        }

        /// <summary>
        /// 如果暂停则等待继续
        /// </summary>
        private async Task WaitIfPausedAsync(CancellationToken cancellationToken)
        {
            while (_isPaused && !cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(500, cancellationToken);
            }
            cancellationToken.ThrowIfCancellationRequested();
        }

        /// <summary>
        /// 检查AI服务状态
        /// </summary>
        private async Task<bool> CheckAIServiceStatusAsync()
        {
            try
            {
                UpdateUI("检查AI服务状态...", true);

                // 获取AI服务管理器
                var aiServiceManager = App.ServiceProvider?.GetService(typeof(IAIService)) as AIServiceManager;
                if (aiServiceManager == null)
                {
                    MessageBox.Show("AI服务管理器未初始化，请重启应用程序", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // 检查当前提供者
                var currentProvider = aiServiceManager.GetCurrentProviderName();
                if (string.IsNullOrEmpty(currentProvider))
                {
                    var result = MessageBox.Show("未设置AI模型提供者。是否打开AI模型配置？", "提示",
                        MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        // 打开AI模型配置窗口
                        var configWindow = new AIModelConfigWindow(App.ServiceProvider!);
                        configWindow.ShowDialog();
                    }
                    return false;
                }

                // 检查当前模型
                var currentModel = aiServiceManager.GetCurrentModel();
                if (currentModel == null)
                {
                    var result = MessageBox.Show($"未设置{currentProvider}模型。是否打开AI模型配置？", "提示",
                        MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        // 打开AI模型配置窗口
                        var configWindow = new AIModelConfigWindow(App.ServiceProvider!);
                        configWindow.ShowDialog();
                    }
                    return false;
                }

                // 测试AI服务连接
                try
                {
                    var testResult = await aiServiceManager.GenerateTextAsync("测试", 10, 0.7f);
                    if (string.IsNullOrEmpty(testResult))
                    {
                        MessageBox.Show("AI服务连接测试失败，请检查模型配置", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"AI服务连接测试失败：{ex.Message}\n\n请检查：\n1. 模型服务是否正在运行\n2. 网络连接是否正常\n3. API密钥是否有效",
                        "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                UpdateUI("AI服务状态检查完成", false);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查AI服务状态失败");
                MessageBox.Show($"检查AI服务状态失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        private async void CheckNetwork_Click(object sender, RoutedEventArgs e)
        {
            await CheckNetworkStatusAsync();
        }

        private async Task CheckNetworkStatusAsync()
        {
            try
            {
                NetworkStatusText.Visibility = Visibility.Visible;
                NetworkStatusText.Text = "网络状态: 检查中...";

                var networkStatus = await _stepByStepService.GetNetworkStatusMessageAsync();
                NetworkStatusText.Text = $"网络状态: {networkStatus}";

                // 根据网络状态设置颜色
                if (networkStatus.Contains("正常"))
                {
                    NetworkStatusText.Foreground = Brushes.Green;
                }
                else if (networkStatus.Contains("异常") || networkStatus.Contains("失败"))
                {
                    NetworkStatusText.Foreground = Brushes.Red;
                }
                else
                {
                    NetworkStatusText.Foreground = Brushes.Orange;
                }
            }
            catch (Exception ex)
            {
                NetworkStatusText.Text = $"网络状态: 检查失败 - {ex.Message}";
                NetworkStatusText.Foreground = Brushes.Red;
                _logger.LogError(ex, "检查网络状态失败");
            }
        }

        // 辅助方法
        private bool ValidateBasicInfo()
        {
            if (string.IsNullOrWhiteSpace(BookTitleTextBox.Text))
            {
                MessageBox.Show("请输入书籍标题", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                BookTitleTextBox.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(CreativeDirectionTextBox.Text))
            {
                MessageBox.Show("请输入创作方向", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                CreativeDirectionTextBox.Focus();
                return false;
            }

            if (CurrentProject == null)
            {
                MessageBox.Show("请先选择或创建项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }

            return true;
        }

        private async Task InitializeStateIfNeededAsync()
        {
            if (_currentState != null)
                return;

            try
            {
                // 尝试加载现有状态
                _currentState = await _stepByStepService.LoadStateAsync(CurrentProject!.RootPath);

                if (_currentState == null)
                {
                    // 创建新状态
                    _currentState = new StepByStepWritingService.StepExecutionState
                    {
                        BookTitle = BookTitleTextBox.Text.Trim(),
                        CreativeDirection = CreativeDirectionTextBox.Text.Trim(),
                        VolumeCount = int.Parse(VolumeCountTextBox.Text),
                        ChapterCount = int.Parse(ChapterCountTextBox.Text),
                        WordsPerChapter = int.Parse(WordsPerChapterTextBox.Text),
                        ProjectPath = CurrentProject.RootPath
                    };

                    // 创建或获取小说项目
                    var novelCreationService = App.ServiceProvider?.GetService(typeof(INovelCreationService))
                        as INovelCreationService;

                    if (novelCreationService != null)
                    {
                        var novelProject = await novelCreationService.CreateNovelProjectAsync(
                            CurrentProject.Id,
                            _currentState.BookTitle,
                            _currentState.CreativeDirection,
                            _currentState.ChapterCount,
                            _currentState.WordsPerChapter);

                        _currentState.NovelProjectId = novelProject.Id;
                    }
                }

                ProjectStatusText.Text = $"项目: {_currentState.BookTitle} | 状态: 已初始化";
                UpdateStepIcons();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化执行状态失败");
                MessageBox.Show($"初始化执行状态失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void UpdateUI(string status, bool isExecuting)
        {
            StatusText.Text = status;
            ExecutionProgressBar.Visibility = isExecuting ? Visibility.Visible : Visibility.Collapsed;

            if (!isExecuting)
            {
                ExecutionProgressBar.Value = 0;
            }
        }

        private bool IsNetworkError(string errorMessage)
        {
            return errorMessage.Contains("SSL connection") ||
                   errorMessage.Contains("远程主机强迫关闭") ||
                   errorMessage.Contains("connection") ||
                   errorMessage.Contains("network") ||
                   errorMessage.Contains("timeout") ||
                   errorMessage.Contains("HttpRequestException") ||
                   errorMessage.Contains("SocketException");
        }

        /// <summary>
        /// 获取详细的错误信息和恢复建议
        /// </summary>
        private string GetDetailedErrorMessage(Exception ex)
        {
            var message = ex.Message;

            // LM Studio相关错误
            if (message.Contains("BadGateway") || message.Contains("502"))
            {
                return "LM Studio服务器错误（502 Bad Gateway）\n\n" +
                       "可能原因：\n" +
                       "• 模型负载过高或内存不足\n" +
                       "• 模型推理过程中出现内部错误\n" +
                       "• 输入内容过长，超过模型上下文限制\n\n" +
                       "建议解决方案：\n" +
                       "• 重启LM Studio并重新加载模型\n" +
                       "• 检查显存和内存使用情况\n" +
                       "• 尝试使用较小的模型\n" +
                       "• 减少单次生成的字数要求";
            }

            // 章节生成失败
            if (message.Contains("章节生成失败"))
            {
                return "章节内容生成失败\n\n" +
                       "这通常是由于AI模型无法生成足够长度的内容导致的。\n\n" +
                       "建议解决方案：\n" +
                       "• 检查AI模型配置中的MaxTokens设置\n" +
                       "• 确保LM Studio模型正常运行\n" +
                       "• 尝试重新生成该章节\n" +
                       "• 考虑调整目标字数要求";
            }

            // 网络错误
            if (IsNetworkError(message))
            {
                return "网络连接问题\n\n" +
                       "系统检测到网络连接异常。\n\n" +
                       "建议解决方案：\n" +
                       "• 检查网络连接状态\n" +
                       "• 确认LM Studio服务正在运行\n" +
                       "• 检查防火墙设置\n" +
                       "• 稍后重试操作";
            }

            // 默认错误处理
            return $"执行过程中发生错误\n\n错误信息：{message}\n\n" +
                   "建议解决方案：\n" +
                   "• 检查AI模型配置\n" +
                   "• 确保所有服务正常运行\n" +
                   "• 尝试重新执行操作\n" +
                   "• 如问题持续，请查看详细日志";
        }

        /// <summary>
        /// 显示详细错误对话框
        /// </summary>
        private void ShowDetailedErrorDialog(Exception ex)
        {
            var detailWindow = new Window
            {
                Title = "详细错误信息",
                Width = 600,
                Height = 400,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this
            };

            var scrollViewer = new ScrollViewer
            {
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                Margin = new Thickness(10)
            };

            var textBlock = new TextBlock
            {
                Text = $"错误类型：{ex.GetType().Name}\n\n" +
                       $"错误信息：{ex.Message}\n\n" +
                       $"堆栈跟踪：\n{ex.StackTrace}",
                TextWrapping = TextWrapping.Wrap,
                FontFamily = new FontFamily("Consolas"),
                FontSize = 12
            };

            scrollViewer.Content = textBlock;
            detailWindow.Content = scrollViewer;
            detailWindow.ShowDialog();
        }

        #region 书籍基本信息保存和加载

        /// <summary>
        /// 保存书籍基本信息
        /// </summary>
        private async void SaveBasicInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var basicInfo = GetCurrentBasicInfo();
                if (basicInfo == null)
                {
                    MessageBox.Show("请先填写完整的书籍基本信息", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var (success, message) = await _bookBasicInfoService.SaveBasicInfoAsync(basicInfo);

                if (success)
                {
                    MessageBox.Show("书籍基本信息保存成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    _logger.LogInformation($"书籍基本信息保存成功: {basicInfo.BookTitle}");
                }
                else
                {
                    MessageBox.Show($"保存失败: {message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    _logger.LogError($"书籍基本信息保存失败: {message}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存书籍基本信息时发生错误");
                MessageBox.Show($"保存时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载书籍基本信息
        /// </summary>
        private async void LoadBasicInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (CurrentProject == null)
                {
                    MessageBox.Show("请先选择项目", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var basicInfo = await _bookBasicInfoService.LoadBasicInfoAsync(CurrentProject.RootPath);

                if (basicInfo == null)
                {
                    // 尝试显示历史保存的配置选择对话框
                    await ShowSavedConfigsDialog();
                    return;
                }

                // 应用加载的基本信息到UI
                ApplyBasicInfoToUI(basicInfo);

                MessageBox.Show("书籍基本信息加载成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                _logger.LogInformation($"书籍基本信息加载成功: {basicInfo.BookTitle}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载书籍基本信息时发生错误");
                MessageBox.Show($"加载时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取当前UI中的书籍基本信息
        /// </summary>
        private BookBasicInfo? GetCurrentBasicInfo()
        {
            try
            {
                var bookTitle = BookTitleTextBox.Text?.Trim();
                if (string.IsNullOrEmpty(bookTitle))
                {
                    return null;
                }

                if (!int.TryParse(VolumeCountTextBox.Text, out int volumeCount) || volumeCount < 1 || volumeCount > 50)
                {
                    return null;
                }

                if (!int.TryParse(ChapterCountTextBox.Text, out int chapterCount))
                {
                    return null;
                }

                if (!int.TryParse(WordsPerChapterTextBox.Text, out int wordsPerChapter))
                {
                    return null;
                }

                return new BookBasicInfo
                {
                    BookTitle = bookTitle,
                    VolumeCount = volumeCount,
                    ChapterCount = chapterCount,
                    WordsPerChapter = wordsPerChapter,
                    CreativeDirection = CreativeDirectionTextBox.Text?.Trim() ?? string.Empty,
                    ProjectPath = CurrentProject?.RootPath ?? string.Empty,
                    // 新增字段
                    AuthorName = AuthorNameTextBox.Text?.Trim() ?? string.Empty,
                    Genre = (GenreComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString() ?? "都市修仙",
                    TargetWordCount = int.TryParse(TargetWordCountTextBox.Text, out var targetWords) ? targetWords : 650000,
                    SegmentWords = int.TryParse(SegmentWordsTextBox.Text, out var segmentWords) ? segmentWords : 1000,
                    ReviewChapters = int.TryParse(ReviewChaptersTextBox.Text, out var reviewChapters) ? reviewChapters : 3,
                    WritingStyle = (WritingStyleComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString() ?? "流畅自然",
                    AutoSave = AutoSaveCheckBox.IsChecked == true,
                    GenerateOutlineFirst = GenerateOutlineFirstCheckBox.IsChecked == true,
                    UseReferenceContent = UseReferenceContentCheckBox.IsChecked == true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取当前书籍基本信息失败");
                return null;
            }
        }

        /// <summary>
        /// 将书籍基本信息应用到UI
        /// </summary>
        private void ApplyBasicInfoToUI(BookBasicInfo basicInfo)
        {
            try
            {
                BookTitleTextBox.Text = basicInfo.BookTitle;
                VolumeCountTextBox.Text = basicInfo.VolumeCount.ToString();
                ChapterCountTextBox.Text = basicInfo.ChapterCount.ToString();
                WordsPerChapterTextBox.Text = basicInfo.WordsPerChapter.ToString();
                CreativeDirectionTextBox.Text = basicInfo.CreativeDirection;

                // 应用新增字段
                AuthorNameTextBox.Text = basicInfo.AuthorName ?? string.Empty;
                TargetWordCountTextBox.Text = basicInfo.TargetWordCount.ToString();
                SegmentWordsTextBox.Text = basicInfo.SegmentWords.ToString();
                ReviewChaptersTextBox.Text = basicInfo.ReviewChapters.ToString();

                // 设置下拉框选项
                SetComboBoxSelection(GenreComboBox, basicInfo.Genre ?? "都市修仙");
                SetComboBoxSelection(WritingStyleComboBox, basicInfo.WritingStyle ?? "流畅自然");

                // 设置复选框
                AutoSaveCheckBox.IsChecked = basicInfo.AutoSave;
                GenerateOutlineFirstCheckBox.IsChecked = basicInfo.GenerateOutlineFirst;
                UseReferenceContentCheckBox.IsChecked = basicInfo.UseReferenceContent;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "应用书籍基本信息到UI失败");
            }
        }

        /// <summary>
        /// 设置下拉框选择项
        /// </summary>
        private void SetComboBoxSelection(ComboBox comboBox, string value)
        {
            try
            {
                for (int i = 0; i < comboBox.Items.Count; i++)
                {
                    if (comboBox.Items[i] is ComboBoxItem item &&
                        item.Content?.ToString() == value)
                    {
                        comboBox.SelectedIndex = i;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"设置下拉框选择项失败: {value}");
            }
        }

        /// <summary>
        /// 显示已保存的配置选择对话框
        /// </summary>
        private async Task ShowSavedConfigsDialog()
        {
            try
            {
                var savedConfigs = await _bookBasicInfoService.GetAllSavedBasicInfoAsync();

                if (!savedConfigs.Any())
                {
                    MessageBox.Show("没有找到已保存的书籍配置", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 创建选择对话框
                var dialog = new SavedConfigsSelectionDialog(savedConfigs);
                dialog.Owner = this;

                if (dialog.ShowDialog() == true && dialog.SelectedConfig != null)
                {
                    ApplyBasicInfoToUI(dialog.SelectedConfig);
                    MessageBox.Show("配置加载成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示已保存配置对话框失败");
                MessageBox.Show($"显示配置选择对话框时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 自动加载书籍基本信息
        /// </summary>
        private async Task AutoLoadBasicInfo()
        {
            try
            {
                if (CurrentProject == null)
                {
                    return;
                }

                var basicInfo = await _bookBasicInfoService.LoadBasicInfoAsync(CurrentProject.RootPath);

                if (basicInfo != null)
                {
                    // 静默应用加载的基本信息到UI
                    ApplyBasicInfoToUI(basicInfo);
                    _logger.LogInformation($"自动加载书籍基本信息成功: {basicInfo.BookTitle}");

                    // 更新状态显示
                    ProjectStatusText.Text = $"已加载书籍配置: {basicInfo.BookTitle}";
                }
                else
                {
                    _logger.LogInformation("未找到已保存的书籍基本信息");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自动加载书籍基本信息失败");
                // 自动加载失败时不显示错误消息，只记录日志
            }
        }

        #endregion

        #region 逐章生成功能

        /// <summary>
        /// 逐章生成单个章节（细纲→正文→时间线）
        /// </summary>
        private async void SequentialGenerateChapter_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null || !_currentState.VolumeOutlinesCompleted)
                {
                    MessageBox.Show("请先完成卷宗大纲生成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (!int.TryParse(ChapterNumberTextBox.Text, out int chapterNumber) || chapterNumber <= 0)
                {
                    MessageBox.Show("请输入有效的章节号", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                UpdateUI($"开始逐章生成第{chapterNumber}章...", true);

                _cancellationTokenSource = new CancellationTokenSource();
                var progress = new Progress<int>(percentage =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        ExecutionProgressBar.Value = percentage;
                        if (percentage == 10)
                            UpdateUI($"正在生成第{chapterNumber}章细纲...", true);
                        else if (percentage == 50)
                            UpdateUI($"正在生成第{chapterNumber}章正文...", true);
                        else if (percentage == 80)
                            UpdateUI($"正在更新第{chapterNumber}章时间线...", true);
                    });
                });

                var result = await _stepByStepService.GenerateChapterSequentiallyAsync(
                    _currentState, chapterNumber, progress, _cancellationTokenSource.Token);

                if (result.IsSuccess)
                {
                    ContentDisplayTextBox.Text = result.Data?.ToString() ?? "";
                    ContentTitleText.Text = $"第{chapterNumber}章正文";
                    UpdateStepIcons();
                    await _stepByStepService.SaveStateAsync(_currentState);
                    UpdateUI($"第{chapterNumber}章逐章生成完成", false);

                    // 触发项目导航刷新
                    ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    UpdateUI($"第{chapterNumber}章逐章生成失败: {result.Message}", false);
                    MessageBox.Show($"第{chapterNumber}章逐章生成失败：{result.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "逐章生成时发生错误");
                UpdateUI("逐章生成时发生错误", false);
                MessageBox.Show($"逐章生成时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 逐章连续生成相关变量
        private bool _isSequentialGenerating = false;
        private bool _isSequentialPaused = false;
        private CancellationTokenSource? _sequentialCancellationTokenSource;

        /// <summary>
        /// 开始逐章连续生成
        /// </summary>
        private async void StartSequentialGeneration_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentState == null || !_currentState.VolumeOutlinesCompleted)
                {
                    MessageBox.Show("请先完成卷宗大纲生成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (!int.TryParse(StartChapterTextBox.Text, out int startChapter) || startChapter <= 0)
                {
                    MessageBox.Show("请输入有效的起始章节号", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!int.TryParse(EndChapterTextBox.Text, out int endChapter) || endChapter < startChapter)
                {
                    MessageBox.Show("请输入有效的结束章节号（必须大于等于起始章节号）", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                _isSequentialGenerating = true;
                _isSequentialPaused = false;
                _sequentialCancellationTokenSource = new CancellationTokenSource();

                UpdateSequentialGenerationButtonStates();
                UpdateUI($"开始逐章连续生成（第{startChapter}-{endChapter}章）...", true);

                await PerformSequentialGenerationAsync(startChapter, endChapter, _sequentialCancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始逐章连续生成时发生错误");
                MessageBox.Show($"开始逐章连续生成时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isSequentialGenerating = false;
                _isSequentialPaused = false;
                UpdateSequentialGenerationButtonStates();
            }
        }

        /// <summary>
        /// 暂停逐章连续生成
        /// </summary>
        private void PauseSequentialGeneration_Click(object sender, RoutedEventArgs e)
        {
            if (!_isSequentialGenerating || _isSequentialPaused)
            {
                MessageBox.Show("当前没有正在进行的逐章生成任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            _isSequentialPaused = true;
            UpdateSequentialGenerationButtonStates();
            UpdateUI("逐章生成已暂停", false);
            _logger.LogInformation("用户暂停了逐章连续生成");
        }

        /// <summary>
        /// 继续逐章连续生成
        /// </summary>
        private void ResumeSequentialGeneration_Click(object sender, RoutedEventArgs e)
        {
            if (!_isSequentialGenerating || !_isSequentialPaused)
            {
                MessageBox.Show("当前没有暂停的逐章生成任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            _isSequentialPaused = false;
            UpdateSequentialGenerationButtonStates();
            UpdateUI("继续逐章生成...", true);
            _logger.LogInformation("用户继续了逐章连续生成");
        }

        /// <summary>
        /// 停止逐章连续生成
        /// </summary>
        private void StopSequentialGeneration_Click(object sender, RoutedEventArgs e)
        {
            if (!_isSequentialGenerating)
            {
                MessageBox.Show("当前没有正在进行的逐章生成任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            _sequentialCancellationTokenSource?.Cancel();
            _isSequentialGenerating = false;
            _isSequentialPaused = false;
            UpdateSequentialGenerationButtonStates();
            UpdateUI("逐章生成已停止", false);
            _logger.LogInformation("用户停止了逐章连续生成");
        }

        /// <summary>
        /// 执行逐章连续生成
        /// </summary>
        private async Task PerformSequentialGenerationAsync(int startChapter, int endChapter, CancellationToken cancellationToken)
        {
            try
            {
                var totalChapters = endChapter - startChapter + 1;
                var completedChapters = 0;

                for (int chapterNumber = startChapter; chapterNumber <= endChapter; chapterNumber++)
                {
                    // 检查是否被取消
                    cancellationToken.ThrowIfCancellationRequested();

                    // 检查是否被暂停
                    while (_isSequentialPaused && !cancellationToken.IsCancellationRequested)
                    {
                        await Task.Delay(500, cancellationToken);
                    }

                    // 再次检查是否被取消
                    cancellationToken.ThrowIfCancellationRequested();

                    UpdateUI($"正在生成第{chapterNumber}章（{completedChapters + 1}/{totalChapters}）...", true);

                    var progress = new Progress<int>(percentage =>
                    {
                        var overallProgress = (completedChapters * 100 + percentage) / totalChapters;
                        Dispatcher.Invoke(() =>
                        {
                            ExecutionProgressBar.Value = overallProgress;
                        });
                    });

                    var result = await _stepByStepService.GenerateChapterSequentiallyAsync(
                        _currentState, chapterNumber, progress, cancellationToken);

                    if (result.IsSuccess)
                    {
                        completedChapters++;
                        var overallProgress = (completedChapters * 100) / totalChapters;
                        ExecutionProgressBar.Value = overallProgress;

                        UpdateUI($"第{chapterNumber}章生成完成 ({completedChapters}/{totalChapters})", false);

                        // 显示当前章节内容
                        ContentDisplayTextBox.Text = result.Data?.ToString() ?? "";
                        ContentTitleText.Text = $"第{chapterNumber}章正文";

                        // 保存状态
                        await _stepByStepService.SaveStateAsync(_currentState);

                        // 触发项目导航刷新
                        ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);

                        // 短暂延迟，避免API限制
                        await Task.Delay(2000, cancellationToken);
                    }
                    else
                    {
                        _logger.LogError($"第{chapterNumber}章生成失败: {result.Message}");
                        UpdateUI($"第{chapterNumber}章生成失败: {result.Message}", false);

                        var continueResult = MessageBox.Show(
                            $"第{chapterNumber}章生成失败：{result.Message}\n\n是否继续生成下一章？",
                            "生成失败",
                            MessageBoxButton.YesNo,
                            MessageBoxImage.Warning);

                        if (continueResult == MessageBoxResult.No)
                        {
                            break;
                        }
                    }
                }

                UpdateUI($"逐章连续生成完成，共生成{completedChapters}章", false);
                _logger.LogInformation($"逐章连续生成完成，共生成{completedChapters}章");
            }
            catch (OperationCanceledException)
            {
                UpdateUI("逐章连续生成已取消", false);
                _logger.LogInformation("逐章连续生成被用户取消");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "逐章连续生成过程中发生错误");
                UpdateUI($"逐章连续生成失败: {ex.Message}", false);
                MessageBox.Show($"逐章连续生成失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更新逐章生成按钮状态
        /// </summary>
        private void UpdateSequentialGenerationButtonStates()
        {
            Dispatcher.Invoke(() =>
            {
                StartSequentialGenerationButton.IsEnabled = !_isSequentialGenerating && _currentState?.VolumeOutlinesCompleted == true;
                PauseSequentialGenerationButton.IsEnabled = _isSequentialGenerating && !_isSequentialPaused;
                ResumeSequentialGenerationButton.IsEnabled = _isSequentialGenerating && _isSequentialPaused;
                StopSequentialGenerationButton.IsEnabled = _isSequentialGenerating;

                StartChapterTextBox.IsEnabled = !_isSequentialGenerating && _currentState?.VolumeOutlinesCompleted == true;
                EndChapterTextBox.IsEnabled = !_isSequentialGenerating && _currentState?.VolumeOutlinesCompleted == true;
                SequentialGenerateChapterButton.IsEnabled = !_isSequentialGenerating && _currentState?.VolumeOutlinesCompleted == true;
            });
        }

        #endregion
    }
}
